﻿(*
    The MIT License

    Copyright (c)2010 Fondevila Ltd

    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in
    all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
    THE SOFTWARE.
*)


namespace uk.co.fondevila.GoGo.Reader

open System
open System.Net
open System.Xml
open System.Linq
open System.Xml.Linq
open System.Collections.Generic
open System.ServiceModel.Syndication
open uk.co.fondevila.GoGo
open uk.co.fondevila.GoGo.Exceptions
open uk.co.fondevila.GoGo.Reader.ReaderCommandFormatter


type public ReaderService (username: string, password: string, source: string) =
    inherit GoGoService("reader", username, password, source)
    interface IDisposable with
        member s.Dispose() = ()

    member public r.getFeedContent(feedUrl: string, limit: int) =
        try
            r.getItemsFromFeed(String.Format("{0}{1}", ReaderUrl.FeedUrl, System.Uri.EscapeDataString(feedUrl)), limit)
        with
        | :? WebException as wex ->
            match wex.Response with
            | :? HttpWebResponse as rsp when rsp.StatusCode = HttpStatusCode.NotFound ->
                raise(new FeedNotFoundException(feedUrl))
            | _ -> reraise()

    member public s.addSubscription(feed: string) =
        s.postRequest(ReaderCommand.SubscriptionAdd, new GoGoParameter("quickadd",  feed))

    member public s.tagSubscription(feed: string, folder: string) =
        s.postRequest(ReaderCommand.SubscriptionEdit,
                new GoGoParameter("a", ReaderUrl.LabelPath + folder), 
                new GoGoParameter("s", "feed/" + feed), 
                new GoGoParameter("ac", "edit"))

    member public s.getSubscriptions() =
        let xml = s.Session.getSource(getFullUrl ReaderCommand.SubscriptionList)
        XElement.Parse(xml).Elements(XName.Get "list").Elements(XName.Get "object") |> Seq.map (fun o -> new Subscription(o))

    member public s.addTags(item: ReaderItem, [<ParamArray>] tags: string[]) =
        let arraySize = tags.Length + item.Tags.Count + 2

        let parameters = Array.zeroCreate arraySize
        parameters.[0] <- new GoGoParameter("s", "feed/" + item.Feed.Url.ToString())
        parameters.[1] <- new GoGoParameter("i", item.Id)

        let startParam = 2

        for i in 0..(item.Tags.Count - 1) do
            parameters.[startParam + i] <- new GoGoParameter("a", ReaderUrl.LabelPath + item.Tags.[i])

        for i in 0..(tags.Length - 1) do
            parameters.[startParam + item.Tags.Count + i] <- new GoGoParameter("a", ReaderUrl.LabelPath + tags.[i])

        s.postRequest(ReaderCommand.TagAdd, parameters)


    member public s.renameTag(tag: string, newName: string) =
        s.postRequest(ReaderCommand.TagRename,
            new GoGoParameter("s", ReaderUrl.LabelPath + tag),
            new GoGoParameter("t", tag),
            new GoGoParameter("dest", ReaderUrl.LabelPath + newName))


    member public s.removeTag(tag: string) =
        s.postRequest(ReaderCommand.TagDelete,
            new GoGoParameter("s", ReaderUrl.LabelPath + tag),
            new GoGoParameter("t", tag))


    member public s.removeTag(item: ReaderItem, tag: string)  =
        s.postRequest(ReaderCommand.TagEdit,
            new GoGoParameter("r", ReaderUrl.LabelPath + tag),
            new GoGoParameter("s", "feed/" + item.Feed.Url.ToString()),
            new GoGoParameter("i", item.Id))


    member public s.getTags() =
        let xml = s.Session.getSource(getFullUrl ReaderCommand.TagList)
        let tags = new List<string>()

        XElement.Parse(xml).Elements(XName.Get "list").Descendants(XName.Get "string")
        |> Seq.filter (fun t -> t.Attribute(XName.Get "name").Value = "id" && t.Value.Contains("/label/"))
        |> Seq.iter (fun t ->
                        let tag = t.Value.Substring(t.Value.LastIndexOf('/') + 1, 
                                    t.Value.Length - t.Value.LastIndexOf('/') - 1)
                        tags.Add(tag) )
        tags


    member public s.getTagItems(tag: string, limit: int) =
        s.getItemsFromFeed(String.Format("{0}{1}", ReaderUrl.LabelPath, System.Uri.EscapeDataString(tag)), limit)


    member public s.addState(item: ReaderItem, state: State) =
        s.postRequest(ReaderCommand.TagEdit,
            new GoGoParameter("a", ReaderUrl.StatePath + StateFormatter.ToString(state)),
            new GoGoParameter("i", item.Id),
            new GoGoParameter("s", "feed/" + item.Feed.Url.ToString()))


    member public s.removeState(item: ReaderItem, state: State) =
        s.postRequest(ReaderCommand.TagEdit,
            new GoGoParameter("r", ReaderUrl.StatePath + StateFormatter.ToString(state)),
            new GoGoParameter("i", item.Id),
            new GoGoParameter("s", "feed/" + item.Feed.Url.ToString()))


    member public s.getStateItems(state: State, limit: int) =
        s.getItemsFromFeed(String.Format("{0}{1}", ReaderUrl.StateUrl, StateFormatter.ToString(state)), limit)

    member public s.postRequest(command: ReaderCommand, [<ParamArray>] postFields: GoGoParameter[]) =
        s.Session.postRequest(ReaderCommandFormatter.getFullUrl(command), postFields)
        
    member public s.getItemsFromFeed(url: string, limit: int) =
        let feed = s.Session.getFeed(url, new GoGoParameter("n", limit.ToString()))
        feed.Items |> Seq.map (fun i -> new ReaderItem(i))



